package br.com.pedidos.servidor.endpoint;

import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint("/celular")
public class CelularEndpoint {

    private static Set<Session> clients = Collections.synchronizedSet(new HashSet<Session>());

    private static Session session;

    @OnOpen
    public void handleOpen(Session session) {
        clients.add(session);
        System.out.println("Celular " + session + " está conectado...");
    }

    @OnMessage
    public void handleMessage(String msg, Session session) throws IOException {
        System.out.println("mensagem recebida: " + msg);

    }

    @OnClose
    public void handleClose(Session session) {
        System.out.println("Celular " + session + " está desconectado...");
        clients.remove(session);
    }

    @OnError
    public void handleErrod(Throwable t) {
        System.out.println("Celular desconectado via erro...");
        t.printStackTrace();
    }

    public static void atualizarHistoricoECancelar() throws IOException {

        synchronized (clients) {
            // Faz a iteração nas sessões conectadas
            // e transmite as mensagens recebidas
            for (Session client : clients) {
                if (!client.equals(session)) {
                    client.getBasicRemote().sendText("cancelar");

                }
            }
        }
    }
    
        public static void atualizarHistorico() throws IOException {

        synchronized (clients) {
            // Faz a iteração nas sessões conectadas
            // e transmite as mensagens recebidas
            for (Session client : clients) {
                if (!client.equals(session)) {
                    client.getBasicRemote().sendText("historico");

                }
            }
        }
    }

    // Getters and Setters    
    public static Set<Session> getClients() {
        return clients;
    }

    public static void setClients(Set<Session> clients) {
        CelularEndpoint.clients = clients;
    }

}
